<template>
  <div class="route-page">
    <!--    <section class="tab-header">-->
    <!--      <a-tabs :activeKey="currentTabKey" @change="onTabChange">-->
    <!--        <a-tab-pane-->
    <!--          v-for="item of tabList"-->
    <!--          :key="item.key"-->
    <!--          :tab="item.tab"-->
    <!--        ></a-tab-pane>-->
    <!--        <template #rightExtra>-->
    <!--          <a-button-->
    <!--            v-permission="['processContract', 'curd', 'add']"-->
    <!--            type="primary"-->
    <!--            @click="editRecord()"-->
    <!--          >-->
    <!--            <template #icon>-->
    <!--              <PlusOutlined />-->
    <!--            </template>-->
    <!--            审批流程-->
    <!--          </a-button>-->
    <!--        </template>-->
    <!--      </a-tabs>-->
    <!--    </section>-->
    <a-card
      class="card-with-title-page card-approval"
      :tab-list="tabList"
      :active-tab-key="currentTabKey"
      @tabChange="(key) => onTabChange(key)"
    >
      <template #tabBarExtraContent>
        <a-button
          v-permission="['processContract', 'curd', 'add']"
          type="primary"
          @click="editRecord()"
        >
          <template #icon>
            <PlusOutlined />
          </template>
          审批流程
        </a-button>
      </template>
      <!-- 表格 -->
      <a-table
        sticky
        :columns="currentTabKey != 'retreat' ? columns : columns1"
        :data-source="dataList"
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        :scroll="{ x: 'max-content' }"
      >
        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.key === 'buildList'">
            <a-popover>
              <template #content>
                <a-row style="width: 240px;">
                  <a-col v-for="(item, index) of text" :key="index">
                    <a-tag
                     color="blue"
                     class="mr-5 mb-5 mt-5"
                     >
                     {{ item }}
                   </a-tag>
                  </a-col>
                </a-row>
              </template>
              <div class="build-tip hide-scroller-bar">
                <a-tag
                  color="blue"
                  class="mr-5 mb-5 mt-5"
                  v-for="(item, index) of text"
                  :key="index"
                  >
                  {{ item }}
                </a-tag>
              </div>
            </a-popover>
          </template>
          <template v-if="column.key === 'status'">
            <a-badge v-if="text == 1" color="green" text="启用中" />
            <a-badge v-if="text == 0" color="red" text="已禁用" />
          </template>
          <template v-if="column.key === 'retreat_name'">
            <div style="max-width: 210px;">
              <div v-if="record.retreat_name && record.retreat_name.length > 0">
                <a-tag v-for="item in record.retreat_name" class="mr-5 mb-5 mt-5" color="blue">{{item}}</a-tag>
              </div>
              <div v-else>--</div>
            </div>
          </template>
          <template v-if="column.key === 'action'">
            <a-button
              type="link"
              v-permission="['processContract', 'curd', 'edit']"
              @click="editRecord(record.id)"
            >
              编辑
            </a-button>
            <a-button
              type="link"
              v-permission="['processContract', 'curd', 'delete']"
              danger
              @click="deleteRecord(record)"
            >
              删除
            </a-button>
          </template>

        </template>
      </a-table>
    </a-card>
    <approval-setting
      :visible="editVisible"
      :id="currentId"
      :addType="currentTabKey"
      @cancel="handleEditCancel"
      @success="handleEditSuccess"
    />
  </div>
</template>

<script>
import { defineComponent, ref, watch, computed, toRefs, reactive  } from "vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import ApprovalSetting from "./modules/ApprovalSetting.vue";
import request from "../../../common/utils/request";
import utils from "../../../common/utils/utils";
import { message } from "ant-design-vue";
import store from "../../../store";
import { useRoute } from "vue-router";

export default defineComponent({
  name: "processContract",
  components: { PlusOutlined, ApprovalSetting },
  setup() {
    const $route = useRoute();
    /**
     * @description: 分页信息
     */
    const page = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: pageSize.value,
      showSizeChanger: true,
    }));

    const state = reactive({
      build_ids: [],
      renting_ids: [],
      rentingList : [
        {value: 1 , text:'到期退租'},
        {value: 2 , text:'换房退租'},
        {value: 3 , text:'违约退租'},
        {value: 4 , text:'协商退租'},
      ]
    });

    // 获取项目-楼宇列表
    const villageList = ref([]);
    const buildListes = ref([]);

    const getVillageList = () => {
      request.get("/org", "/process/getProjectBuildAll").then((res) => {
        buildListes.value = res.list.map((item) => ({
          value: item.id,
          text: item.name,
        }));
      });
    };

    const columns = computed(() => [
      {
        title: "流程名",
        dataIndex: "name",
        key: "name",
      },
      {
        title: "节点数",
        dataIndex: "node_num",
        key: "node_num",
        width: 80,
      },
      {
        title: "审批人数",
        dataIndex: "reviewer_num",
        key: "reviewer_num",
        width: 80,
      },
      {
        title: "已应用楼宇",
        dataIndex: "buildList",
        key: "buildList",
        width: 300
      },
      {
        title: "状态",
        dataIndex: "status",
        key: "status",
      },
      {
        title: "操作",
        dataIndex: "id",
        key: "action",
        fixed: "right",
      },
    ]);

    const columns1 = computed(() => [
      {
        title: "流程名",
        dataIndex: "name",
        key: "name",
      },
      {
        title: "适用退租类型",
        dataIndex: "retreat_name",
        key: "retreat_name",
        filters: state.rentingList,
        filteredValue: state.renting_ids || null,

      },
      {
        title: "节点数",
        dataIndex: "node_num",
        key: "node_num",
        width: 80,
      },
      {
        title: "审批人数",
        dataIndex: "reviewer_num",
        key: "reviewer_num",
        width: 80,
      },
      {
        title: "已应用楼宇",
        dataIndex: "buildList",
        key: "buildList",
        width: 300,
        filters: buildListes.value,
        filteredValue: state.build_ids || null,
      },
      {
        title: "状态",
        dataIndex: "status",
        key: "status",
      },
      {
        title: "操作",
        dataIndex: "id",
        key: "action",
        fixed: "right",
      },
    ]);

    const handleTableChange = (pager, filters, sorter) => {
      page.value = pager.current;
      pageSize.value = pager.pageSize;
      if (filters.buildList) {
        state.build_ids = filters.buildList;
      }else {
        state.build_ids = []
      }
      if (filters.retreat_name) {
        state.renting_ids = filters.retreat_name;
      }else {
        state.renting_ids = []
      }
      getTableData();
    };

    /**
     * @description: 表格数据
     */
    const loading = ref(false);
    const dataList = ref([]);
    watch([page, pageSize], () => {
      getTableData();
    });
    const getTableData = () => {
      loading.value = true;
      request
        .get("/org", "/process/contract", {
          page: page.value,
          limit: pageSize.value,
          type: currentTabKey.value,
          build: {
            buildId: state.build_ids
          },
          retreat_type: JSON.stringify(state.renting_ids),
        })
        .then((res) => {
          let list = res.list;

          if(currentTabKey.value == 'retreat'){
            for (let i = 0; i < list.length; i++) {
              list[i].retreat_name = []
              if( list[i].retreat_type.length > 0){
                for (let j = 0; j < list[i].retreat_type.length; j++) {
                  if(list[i].retreat_type[j] == 1){
                    list[i].retreat_name.push('到期退租')
                  }
                  if(list[i].retreat_type[j] == 2){
                    list[i].retreat_name.push('换房退租')
                  }
                  if(list[i].retreat_type[j] == 3){
                    list[i].retreat_name.push('违约退租')
                  }
                  if(list[i].retreat_type[j] == 4){
                    list[i].retreat_name.push('协商退租')
                  }
                }
              }
            }
          }
          dataList.value = list
          total.value = Number(res.total);
        })
        .finally(() => {
          loading.value = false;
        });
    };

    /**
     * @description: 增删改操作
     */
    // 编辑、添加
    const editVisible = ref(false);
    const currentId = ref(0);
    const editRecord = (id) => {
      editVisible.value = true;
      currentId.value = id || 0;
    };
    const handleEditCancel = () => {
      editVisible.value = false;
      currentId.value = 0;
    };
    const handleEditSuccess = () => {
      handleEditCancel();
      page.value = 1;
      getTableData();
    };

    // 删除
    const deleteRecord = (record) => {
      utils.modalConfirm({
        content: `确认删除合同审批流程“${record.name}”吗？`,
        onOk: () => {
          request
            .del("/org", "/process/contract", {
              id: record.id,
              needMsg: true,
            })
            .then((res) => {
              message.success(res.msg || "删除成功！");
              getTableData();
            });
        },
      });
    };

    // 切换tab
    const currentTabKey = ref("");
    const onTabChange = (key) => {
      console.log("onTabChange", key);
      if (key == currentTabKey.value) {
        return;
      }
      currentTabKey.value = key;
      page.value = 1;
      getTableData();
    };

    // 获取横向tab
    const tabList = ref([]);
    const getTabList = () => {
      request.get("/org", "/process/contract/typeList").then((res) => {
        let list = [];
        if (res.typeList) {
          for (let key in res.typeList) {
            list.push({
              key,
              tab: res.typeList[key],
            });
          }
          currentTabKey.value = $route.query.type || list[0].key;
          getTableData();
        }
        store.dispatch("SetContractAplTypeList", list);
        tabList.value = list;
      });
    };

    // 初始化
    const init = () => {
      getVillageList()
      getTabList();
    };

    init();

    return {
      ...toRefs(state),
      dataList,
      columns,
      columns1,
      loading,
      pagination,
      editVisible,
      currentId,
      tabList,
      currentTabKey,
      handleEditCancel,
      handleEditSuccess,
      editRecord,
      deleteRecord,
      handleTableChange,
      onTabChange,
      villageList,
      buildListes,
      getVillageList,
    };
  },
});

</script>

<style lang="less" scoped>
.tab-header {
  background: #fff;
  padding: 12px;
}
.card-approval {
  :deep(.ant-tabs-tab) {
    font-size: 14px !important;
    padding: 14px 0 !important;
  }
}
.build-tip{
  width: 300px;
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;

}
</style>
